# -*- coding:utf-8 -*-
# @FileName :game_base.py
# @Created  :2024/9/29
# @Author   :天空之城
from game.betting import Betting
from game.deck import Deck
from game.hand_evaluator import HandEvaluator


class BaseGame:
    def __init__(self, players):
        """
        BaseGame 类用于管理德州扑克游戏的基础流程
        :param players: list 玩家列表，每个元素应为 Player 对象
        """
        self.deck = Deck()
        self.betting = Betting()
        self.players = players
        self.community_cards = []
        self.dealer_position = 0

    def play_flop(self):
        self.community_cards = self.deck.deal(3)
        print(f"翻牌: {self.community_cards}")

    def play_turn(self):
        self.community_cards.extend(self.deck.deal(1))
        print(f"转牌: {self.community_cards[-1]}")

    def play_river(self):
        self.community_cards.extend(self.deck.deal(1))
        print(f"河牌: {self.community_cards[-1]}")

    def deal_cards(self):
        for player in self.players:
            player.receive_cards(self.deck.deal(2))
            print(f"给玩家 {player.name} 发牌: {player.hole_cards}")

    def reset_game(self):
        """
        重置游戏状态，准备下一局
        """
        self.deck = Deck()
        self.community_cards = []
        self.betting.reset()
        self.dealer_position = (self.dealer_position + 1) % len(self.players)
        for player in self.players:
            player.reset_for_new_round()

    def showdown(self):
        """
        游戏摊牌阶段，确定赢家

        :return: 返回赢家 Player 对象
        """
        best_hand = None  # 当前最好的手牌信息
        winner = None  # 当前的赢家

        for player in self.players:
            # 将玩家的手牌和公共牌组合成完整的牌
            full_hand = player.hole_cards + self.community_cards
            evaluator = HandEvaluator(full_hand)
            # 获取当前玩家的手牌信息
            hand_rank, best_five_cards, score = evaluator.get_hand_rank()

            # 如果当前没有最好的手牌，或当前玩家的手牌更好，则更新最好的手牌信息和赢家
            if best_hand is None or HandEvaluator.compare_hands(best_five_cards, best_hand[1]) > 0:
                best_hand = (hand_rank, best_five_cards, score)
                winner = player

            # 打印当前玩家的手牌信息
            # print(f'\n玩家：{player.name},\n 牌型: {hand_rank}, 最佳五张牌: {best_five_cards}, 牌型分数: {score}')

        # 打印赢家信息
        # print(f'\n赢家是: {winner.name}, 牌型: {best_hand[0]}, 最佳五张牌: {best_hand[1]}')
        return winner

    def start_game(self):
        raise Exception("游戏逻辑实现")
